'''
https://leetcode.cn/problems/basic-calculator-ii/description/
'''

class Solution:

    def calculate2(self, s: str) -> int:
        s += '+'
        stack = []
        pre = '+'
        num = 0
        for c in s:
            if c == ' ': continue
            if c in '+-*/':
                if pre == '+': stack.append(num)
                elif pre == '-': stack.append(-num)
                elif pre == '*': stack[-1] *= num
                else:
                    # stack[-1] //=  num
                    stack[-1] =  int(stack[-1] / num)
                pre = c
                num = 0
            else:
                num = num * 10 + ord(c) - ord('0')
        return sum(stack)


    def calculate(self, s: str) -> int:
        n = len(s)
        stack = []
        i = 0
        while i < n:
            if s[i] == ' ':
                i += 1
                pass
            elif s[i] == '+' or s[i] == '-':
                stack.append(s[i])
                i += 1
            elif s[i] == '*' or s[i] == '/':
                multiply = s[i] == '*'
                num1 = stack.pop()
                num2 = 0
                i += 1
                while i < n:
                    if s[i] == ' ':
                        i += 1
                    elif s[i].isdigit():
                        num2 = num2 * 10 + int(s[i])
                        i+=1
                    else:
                        break
                stack.append(num1 * num2 if multiply else num1 // num2)
            else:
                num = 0
                while i < n:
                    if s[i] == ' ':
                        i += 1
                    elif s[i].isdigit():
                        num = num * 10 + int(s[i])
                        i += 1
                    else:
                        break
                stack.append(num)
        res = stack[0]
        for i in range(1, len(stack), 2):
            if stack[i] == '+':
                res += stack[i + 1]
            else:
                res -= stack[i + 1]
        return res

s = " 14-3/2 "
print(Solution().calculate(s))

